<template>
    <div>
        <h1 v-if="firstView">请输入用户名进行搜索</h1>
        <h1 v-if="searchStatus">搜索中</h1>
        <h1 v-if="errorMsg">{{errorMsg}}</h1>
        <div class="row" v-show="searchUsers.length>0">
            <div class="card" v-for="(searchUser,index) in searchUsers">
                <a :href="searchUser.url" target="_blank">
                    <img :src="searchUser.avatarUrl" style='width: 100px'/>
                </a>
                <p class="card-text">{{searchUser.name}}</p>
            </div>
        </div>
    </div>
</template>

<script>
    import PubSub from 'pubsub-js'
    import axios from 'axios'
    export default {
        name: "Main",
        data(){
            return {
                firstView:true,
                searchStatus:false,
                errorMsg:'',
                searchUsers:null
            }
        },
        mounted() {
            PubSub.subscribe('search',(msgName,searchName)=>{  //输入了内容点击搜索
                //更新状态(请求中)
                this.firstView = false;
                this.searchStatus = true;
                this.searchUsers = [];
                this.errorMsg = '';
                // 发ajax请求进行搜索
                const url = `https://api.github.com/search/users?q=${searchName}`;
                axios.get(url)
                     .then(response => {
                         //更新状态(请求成功)
                         this.searchStatus = false;
                         this.searchUsers = response.data.items.map(item => ({
                             url: item.html_url,
                             avatarUrl: item.avatar_url,
                             name: item.login
                         }))
                     })
                     .catch(error => {
                         //更新状态(请求失败)
                         this.searchStatus = false;
                         this.errorMsg = '请求失败!'
                     });
            })
        }
    }
</script>

<style scoped>
    .card {
        float: left;
        width: 33.333%;
        padding: .75rem;
        margin-bottom: 2rem;
        border: 1px solid #efefef;
        text-align: center;
    }

    .card > img {
        margin-bottom: .75rem;
        border-radius: 100px;
    }

    .card-text {
        font-size: 85%;
    }

</style>